#!/bin/bash

# auto_install.sh - 自动安装点云处理工具并配置config.yaml

set -e  # 遇到错误立即退出

# 获取脚本所在目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
CONFIG_FILE="${SCRIPT_DIR}/config.yaml"

echo "==========================================="
echo "开始安装点云处理工具..."
echo "脚本目录: ${SCRIPT_DIR}"
echo "==========================================="

# 函数：检查并安装命令
check_and_install_command() {
    local cmd=$1
    local package_name=${2:-$1}  # 第二个参数是包名，默认为命令名
    
    echo -n "检查 $cmd..."
    if ! command -v $cmd &> /dev/null; then
        echo "未找到，正在安装..."
        
        # 检测包管理器
        if command -v apt-get &> /dev/null; then
            # Debian/Ubuntu系统
            sudo apt-get update
            sudo apt-get install -y $package_name
        elif command -v yum &> /dev/null; then
            # CentOS/RHEL系统
            sudo yum install -y $package_name
        elif command -v dnf &> /dev/null; then
            # Fedora系统
            sudo dnf install -y $package_name
        elif command -v pacman &> /dev/null; then
            # Arch Linux系统
            sudo pacman -Sy --noconfirm $package_name
        elif command -v zypper &> /dev/null; then
            # openSUSE系统
            sudo zypper install -y $package_name
        else
            echo "错误: 无法识别的包管理器"
            exit 1
        fi
        
        # 再次检查是否安装成功
        if command -v $cmd &> /dev/null; then
            echo "  ✓ $cmd 安装成功"
        else
            echo "  ✗ $cmd 安装失败，请手动安装"
            exit 1
        fi
    else
        echo "  ✓ 已安装"
    fi
}

# 函数：安装build-essential（包含make, gcc, g++等）
install_build_essential() {
    echo -n "检查build-essential..."
    if ! dpkg -l | grep -q build-essential 2>/dev/null; then
        echo "未找到，正在安装..."
        if command -v apt-get &> /dev/null; then
            sudo apt-get update
            sudo apt-get install -y build-essential
        elif command -v yum &> /dev/null; then
            sudo yum groupinstall -y "Development Tools"
        elif command -v dnf &> /dev/null; then
            sudo dnf groupinstall -y "Development Tools"
        else
            echo "请手动安装编译工具链"
        fi
        echo "  ✓ build-essential 安装完成"
    else
        echo "  ✓ 已安装"
    fi
}

# 检查并安装必要命令
echo "检查并安装必要命令..."
check_and_install_command sudo sudo
check_and_install_command apt-get apt  # apt-get在apt包中
check_and_install_command cmake cmake
check_and_install_command git git

# 安装build-essential（包含make）
install_build_essential

# 检查make是否安装成功
if ! command -v make &> /dev/null; then
    echo "make命令未找到，尝试直接安装make..."
    if command -v apt-get &> /dev/null; then
        sudo apt-get install -y make
    elif command -v yum &> /dev/null; then
        sudo yum install -y make
    fi
fi

# 更新包列表
echo "更新包列表..."
if command -v apt-get &> /dev/null; then
    sudo apt-get update
elif command -v yum &> /dev/null; then
    sudo yum makecache
fi

# 安装系统依赖
echo "安装系统依赖..."
if command -v apt-get &> /dev/null; then
    sudo apt-get install -y libpcl-dev pcl-tools libyaml-cpp-dev pdal \
        libboost-all-dev
elif command -v yum &> /dev/null; then
    sudo yum install -y pcl-devel yaml-cpp-devel pdal \
        boost-devel
fi

# 安装libLAS
echo "安装libLAS..."
if [ -d "${SCRIPT_DIR}/libLAS-master" ]; then
    echo "发现libLAS-master目录，开始编译安装..."
    cd "${SCRIPT_DIR}/libLAS-master"
    if [ ! -d "build" ]; then
        mkdir build
    fi
    cd build
    cmake ..
    make -j$(nproc)
    sudo make install
    echo "libLAS 安装完成"
    
    # 检查libLAS是否安装成功
    echo "检查libLAS安装..."
    if ldconfig -p | grep -q liblas; then
        echo "  ✓ libLAS 库安装成功"
    else
        echo "  ✗ libLAS 库可能未正确安装"
    fi
else
    echo "警告: 未找到libLAS-master目录，跳过libLAS安装"
    echo "请确保libLAS已安装，否则las2pcd可能无法正常工作"
    read -p "是否继续? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# 安装las2pcd
echo "安装las2pcd..."
if [ -d "${SCRIPT_DIR}/las2pcd" ]; then
    echo "发现las2pcd目录，开始编译..."
    cd "${SCRIPT_DIR}/las2pcd"
    if [ ! -d "build" ]; then
        mkdir build
    fi
    cd build
    cmake ..
    make -j$(nproc)
    echo "las2pcd 编译完成"
    
    # 检查编译是否成功
    if [ -f "las2pcd" ]; then
        echo "  ✓ las2pcd 编译成功"
        
        # 创建测试用的空LAS文件
        echo "创建测试文件..."
        TEST_LAS="${SCRIPT_DIR}/test.las"
        if [ ! -f "$TEST_LAS" ]; then
            echo "创建测试LAS文件..."
            cat > "${SCRIPT_DIR}/create_test_las.py" << 'PYEOF'
#!/usr/bin/env python3
import struct

# 创建简单的LAS文件头
las_header = b'LASF' + b'\x02\x00'  # 文件签名和版本
las_header += b'\x00' * 18  # 其他头部字段

# 写入测试文件
with open('test.las', 'wb') as f:
    f.write(las_header)
    print("创建了空的LAS测试文件")
PYEOF
            python3 "${SCRIPT_DIR}/create_test_las.py" 2>/dev/null || echo "注意: 测试文件创建失败，但las2pcd编译成功"
        fi
    else
        echo "  ✗ las2pcd 编译失败"
        exit 1
    fi
else
    echo "错误: 未找到las2pcd目录"
    exit 1
fi

# 安装pointcloud_divider
echo "安装pointcloud_divider-master..."
if [ -d "${SCRIPT_DIR}/pointcloud_divider-master" ]; then
    echo "发现pointcloud_divider-master目录，开始编译..."
    cd "${SCRIPT_DIR}/pointcloud_divider-master"
    if [ ! -d "build" ]; then
        mkdir build
    fi
    cd build
    cmake ..
    make -j$(nproc)
    echo "pointcloud_divider 编译完成"
    
    # 检查编译是否成功
    if find . -name "*pointcloud_divider*" -type f | grep -q .; then
        echo "  ✓ pointcloud_divider 编译成功"
    else
        echo "  ✗ pointcloud_divider 编译失败"
    fi
else
    echo "错误: 未找到pointcloud_divider-master目录"
    exit 1
fi

# 创建输出目录
echo "创建输出目录..."
DEFAULT_OUTPUT_DIR="${SCRIPT_DIR}/converted_pcd"
mkdir -p "${DEFAULT_OUTPUT_DIR}"
echo "输出目录创建于: ${DEFAULT_OUTPUT_DIR}"

# 生成配置文件
echo "生成配置文件..."
cat > "${CONFIG_FILE}" << EOF
# 配置文件路径设置
paths:
  # LAS转PCD转换器路径
  las2pcd_converter: "${SCRIPT_DIR}/las2pcd/build/las2pcd"

  # 点云分割脚本路径
  pointcloud_divider_script: "${SCRIPT_DIR}/pointcloud_divider-master/scripts/pointcloud_divider.sh"

  # 点云分割配置文件路径
  pointcloud_divider_config: "${SCRIPT_DIR}/pointcloud_divider-master/config/default.yaml"

  # 默认输出目录
  default_output_dir: "${DEFAULT_OUTPUT_DIR}"

# 默认参数
defaults:
  # 点云分割参数
  leaf_size: 0.2
  output_name: "pointcloud_map"
EOF

echo "==========================================="
echo "安装完成!"
echo "配置文件已生成: ${CONFIG_FILE}"
echo ""
echo "请检查以下路径是否配置正确:"
echo "1. las2pcd_converter: ${SCRIPT_DIR}/las2pcd/build/las2pcd"
echo "2. pointcloud_divider_script: ${SCRIPT_DIR}/pointcloud_divider-master/scripts/pointcloud_divider.sh"
echo "3. pointcloud_divider_config: ${SCRIPT_DIR}/pointcloud_divider-master/config/default.yaml"
echo "4. default_output_dir: ${DEFAULT_OUTPUT_DIR}"
echo "==========================================="

# 验证安装
echo "验证安装..."
echo "1. 检查las2pcd可执行文件..."
LAS2PCD_PATH="${SCRIPT_DIR}/las2pcd/build/las2pcd"
if [ -f "${LAS2PCD_PATH}" ]; then
    echo "   ✓ las2pcd 存在"
    
    # 尝试不同的方式测试las2pcd
    echo "   测试las2pcd..."
    
    # 方法1: 尝试无参数运行（通常显示帮助）
    echo "   方法1: 测试基本功能..."
    if ${LAS2PCD_PATH} 2>&1 | grep -q -i "usage\|help\|参数\|arg"; then
        echo "     ✓ las2pcd 基本功能正常"
    else
        echo "     ⚠  las2pcd 输出无帮助信息"
    fi
    
    # 方法2: 查看可执行文件信息
    echo "   方法2: 检查文件类型..."
    file ${LAS2PCD_PATH}
    
    # 方法3: 如果有测试文件，尝试实际转换
    if [ -f "${SCRIPT_DIR}/test.las" ]; then
        echo "   方法3: 尝试测试转换..."
        ${LAS2PCD_PATH} "${SCRIPT_DIR}/test.las" "${DEFAULT_OUTPUT_DIR}/test.pcd" 2>&1 | head -5
        echo "     测试完成（可能有错误，这是正常的）"
    fi
    
else
    echo "   ✗ las2pcd 不存在"
fi

echo ""
echo "2. 检查pointcloud_divider脚本..."
DIVIDER_SCRIPT="${SCRIPT_DIR}/pointcloud_divider-master/scripts/pointcloud_divider.sh"
if [ -f "${DIVIDER_SCRIPT}" ]; then
    echo "   ✓ pointcloud_divider.sh 存在"
    # 检查脚本是否有执行权限
    if [ -x "${DIVIDER_SCRIPT}" ]; then
        echo "     ✓ 有执行权限"
    else
        echo "     ⚠ 无执行权限，正在添加..."
        chmod +x "${DIVIDER_SCRIPT}"
    fi
else
    echo "   ✗ pointcloud_divider.sh 不存在"
fi

echo ""
echo "3. 检查配置文件..."
DIVIDER_CONFIG="${SCRIPT_DIR}/pointcloud_divider-master/config/default.yaml"
if [ -f "${DIVIDER_CONFIG}" ]; then
    echo "   ✓ default.yaml 存在"
else
    echo "   ✗ default.yaml 不存在，正在创建默认配置..."
    mkdir -p "$(dirname "${DIVIDER_CONFIG}")"
    cat > "${DIVIDER_CONFIG}" << 'YAMLEOF'
# pointcloud_divider 默认配置
input_dir: "./input_pcd"
output_dir: "./output_pcd"
leaf_size: 0.2
output_name: "pointcloud_map"
YAMLEOF
    echo "     ✓ 已创建默认配置"
fi

echo ""
echo "4. 检查依赖库..."
echo "   libpcl检查..."
if ldconfig -p | grep -q libpcl; then
    echo "     ✓ libpcl 已安装"
else
    echo "     ✗ libpcl 未找到"
fi

echo "   libyaml-cpp检查..."
if ldconfig -p | grep -q yaml-cpp; then
    echo "     ✓ libyaml-cpp 已安装"
else
    echo "     ✗ libyaml-cpp 未找到"
fi

echo ""
echo "所有必需命令状态:"
for cmd in sudo apt-get cmake make git; do
    if command -v $cmd &> /dev/null; then
        echo "  ✓ $cmd: 已安装"
    else
        echo "  ✗ $cmd: 未安装"
    fi
done

echo ""
echo "==========================================="
echo "安装验证完成!"
echo ""
echo "==========================================="

# 清理临时文件
if [ -f "${SCRIPT_DIR}/create_test_las.py" ]; then
    rm -f "${SCRIPT_DIR}/create_test_las.py"
fi
